<script setup lang="ts">

import {computed, inject,watch, reactive, ref} from "vue";
import parcelDeclaration from "@/api/document/parcelDeclaration";
import declareColumns from "@/utils/shipmentTools";
import EditClearance from "@/views/document/shipment/components/actions/editClearance.vue";
import {Message} from "@arco-design/web-vue";
import AddModal from "@cps/actions/addModal.vue";
import tool from '@/utils/tool'
const nameTableRef = ref();
const buttonType = ref('1')
const addModalRef = ref()
const visible = ref({
  edit: false,
});
const record = inject('record');
const pagination=ref(false)
watch( () => record, v => {
    if(v.value?.parcel_declaration.length>10){
      let pageSizeParel=tool.local.get('pageSizeClerance') || 10
      pagination.value={
      size:'small',
      showTotal:true,
      showPageSize:true,
      defaultPageSize:pageSizeParel,
      pageSizeOptions:[10,20,30,50,100]
   }
  
}
},{immediate: true,deep: true})
const tablePaginationChange=(data,extra)=>{
  if(extra.type=='pagination'){
    if(pagination.value.defaultPageSize!=extra.pageSize){
      tool.local.set('pageSizeClerance', extra.pageSize)
    } 
  }
}
const crudRef = inject('crudRef');
const originalColumns = inject('originalDeclareColumns');
const getRecord = inject('getRecord');

// PO Number	中文品名	英文品名	申报单价	数量	材质	产品图片
const nameColumns = computed(() => {
  if (!originalColumns.value) {
    return [
      {title: 'PO Number', data: 'po_number', dataIndex: 'po_number', align: 'center', width: 100},
      {title: '中文品名', data: 'cn_name', dataIndex: 'cn_name', align: 'center', width: 100},
      {title: '英文品名', data: 'en_name', dataIndex: 'en_name', align: 'center', width: 100},
      {title: '申报单价', data: 'price', dataIndex: 'price', width: 100},
      {title: '数量', data: 'quantity', dataIndex: 'quantity', align: 'center', width: 100},
      {title: '材质', data: 'material', dataIndex: 'material', align: 'center', width: 100},
      {title: '图片', dataIndex: 'image', formType: 'upload', type: 'image', width: 100}
    ]
  }
  let columns = declareColumns.formatDeclareColumns(originalColumns.value, 'view')
  columns.push({title: '图片', dataIndex: 'image', formType: 'upload', type: 'image'})
  for(let i = 0 ; i < columns?.length ;i++){
    let item=columns[i]
    item.width=60
    item.align="center"
      // if(item.dataIndex=='price' || item.dataIndex=='quantity' || item.dataIndex=='material'|| item.dataIndex=='weight' || item.dataIndex=='is_magnetic' || item.dataIndex=='is_elec'){
      //   item.width=60
      //       item.align="center"
      // }
  }
  return columns
})
// 货箱编号	PO Number	中文品名	英文品名	申报单价	数量	材质
const parcelColumns = computed(() => {
  if (!originalColumns.value) {
    return [
      {title: '货箱编号', dataIndex: 'number', slotName: 'number', align: 'center'},
      {title: '销售链接', dataIndex: 'sale_url', slotName: 'sale_url', align: 'center'},
      {title: 'PO Number', data: 'po_number', dataIndex: 'po_number', align: 'center'},
      {title: '中文品名', data: 'cn_name', dataIndex: 'cn_name', align: 'center'},
      {title: '英文品名', data: 'en_name', dataIndex: 'en_name', align: 'center'},
      {title: '申报单价', data: 'price', dataIndex: 'price'},
      {title: '数量', data: 'quantity', dataIndex: 'quantity', align: 'center'},
      {title: '材质', data: 'material', dataIndex: 'material', align: 'center'},
    ]
  }
  let columns = declareColumns.formatDeclareColumns(originalColumns.value, 'view')
  columns.unshift({title: '货箱编号', dataIndex: 'number',slotName: 'number', align: 'center'})
  for(let i = 0 ; i < columns?.length ;i++){
    let item=columns[i]
    item.width=60
    item.align="center"
      // if(item.dataIndex=='price' || item.dataIndex=='quantity' || item.dataIndex=='material'|| item.dataIndex=='weight' || item.dataIndex=='is_magnetic' || item.dataIndex=='is_elec'){
      //   item.width=60
      //       item.align="center"
      // }
    if(['sale_url'].includes(item.data)){
      item.width = 100
    }  
    item.slotName = item.data  
    columns[i] = item
  }
  console.log(columns)
  return columns
})
const summary = computed(() => {
  return {
    count: nameTableRef.value?.getTableData().reduce((a, b) => a + b.quantity, 0),
    total: nameTableRef.value?.getTableData().length,
    price: nameTableRef.value?.getTableData().reduce((a, b) => a + b.price * b.quantity, 0).toFixed(2),
    currency: 'USD'
  }
})

const edit = () => {
  visible.value.edit = true
}

const nameConfig = ref({
  api: parcelDeclaration.getAllList,
  showTools: false,
  size: 'mini',
  requestParams: {shipment_id: record.value.id, scene: 'productName'},
})
const imageUploaded = async (v, record) => {
  let res = await parcelDeclaration.update(record.id, {parcel_id: record.parcel_id, image: v})
  if (res.code != 200) {
    Message.error(res.message ?? '修改失败')
    return
  }
  Message.success(v ? '上传成功' : '删除成功')
}

const exportDeclaration = () =>{
  addModalRef.value.open(reactive([
    {
      dataIndex: "shipment_id",
      addDefaultValue: record.value.id,
      formType: "hidden",
      required: true,
    },
    {
      title: "文件",
      dataIndex: "file",
      type: 'file',
      formType: "upload",
      required: true,
    },
  ]), {
    viewType: 'modal',
  }, parcelDeclaration.importExcel, '导入申报信息', function () {
    getRecord()
  })
}
</script>
<script lang="ts">
export default { name: 'shipment:clearanceInfo' }
</script>
<template>
  <a-grid-item :span="24">
    <add-modal ref="addModalRef"></add-modal>
    <a-collapse :default-active-key="['1']" class="g-collapse-no-p">
      <a-collapse-item header="申报信息" key="1">
        <template #header>
          <a-space>
            申报信息
            <a-radio-group type="button" v-model="buttonType" @click.stop="" size="mini">
              <a-radio value="1">品名</a-radio>
              <a-radio value="2">装箱单</a-radio>
            </a-radio-group>
          </a-space>
        </template>
        <template #extra>
          <a-button-group>
            <a-button type="primary" size="mini" @click.stop="edit">
              <icon-edit/>
              编辑
            </a-button>
            <a-button type="primary" size="mini" @click.stop="exportDeclaration()"><icon-upload/>导入申报</a-button>
          </a-button-group>
        </template>
        <a-tabs :active-key="buttonType" type="text" lazy-load :header-padding="false" class="hide-tabs">
          <a-tab-pane key="1">
            <ma-crud :columns="nameColumns" :options="nameConfig" :bordered="false" ref="nameTableRef">
              <template #image="{record}">
                <ma-upload v-model="record.image" :width="50" :height="50"
                           @update:modelValue="(v)=>imageUploaded(v,record)"></ma-upload>
              </template>
              <template #is_elec="{record}">
                <icon-check-circle v-if="record.is_elec == 1" :style="{fontSize:'26px',color:'green'}" />
                <span v-else></span>
              </template>
              <template #is_magnetic="{record}">
                <icon-check-circle v-if="record.is_magnetic == 1" :style="{fontSize:'26px',color:'green'}" />
                <span v-else></span>
              </template>
              <template #sale_url="{ record }">
                <div> <a-link :href="record.sale_url" target="_blank">{{ record.sale_url }}</a-link> </div>
              </template>
            </ma-crud>
          </a-tab-pane>
          <a-tab-pane key="2">
            <a-table :columns="parcelColumns" :data="record?.parcel_declaration" :pagination="pagination" @change="tablePaginationChange" :bordered="false" column-resizable size="mini">
              <template #number="{ record }">
                <div><p>{{ record.number }}</p><p>{{ record.pivot?.ext_number}}</p></div>
              </template>
              <template #sale_url="{ record }">
                <div> <a-link :href="record.sale_url" target="_blank">{{ record.sale_url }}</a-link> </div>
              </template>
            </a-table>
          </a-tab-pane>
        </a-tabs>
        <template v-if="buttonType == 1">
        </template>
        <template v-else>
        </template>
        <a-space class="flex justify-around" style="margin-top: 10px;">
          <div>产品总数：{{ summary.count }}</div>
          <div>申报总价：{{ summary.currency }} {{ summary.price }}</div>
          <div>品名数量：{{ summary.total }}</div>
        </a-space>
      </a-collapse-item>
    </a-collapse>
  </a-grid-item>
  <edit-clearance v-model="visible.edit" v-if="visible.edit"/>
</template>

<style lang="less">
.hide-tabs{
  .arco-tabs-nav{
    display: none;
  }
  .arco-tabs-content{
    padding-top: 0;
  }
}
.upload-image.flex{
  justify-content: center;
}
</style>